package com.tian.service.impl;

import com.tian.entity.market.ChargeGlobalProperty;
import com.tian.entity.user.ChargeUser;
import com.tian.entity.user.ChargeUserIncome;
import com.tian.mapper.market.ChargeGlobalPropertyMapper;
import com.tian.mapper.user.ChargeUserIncomeMapper;
import com.tian.mapper.user.ChargeUserMapper;
import com.tian.message.IncomeMessage;
import com.tian.service.ChargeUserIncomeService;
import com.tian.util.RedisConstantPre;
import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * {@code @description:} 用户收益记录
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024/1/28 11:21
 * {@code @version:} 1.0
 */
@Service
public class ChargeUserIncomeServiceImpl implements ChargeUserIncomeService {

    @Resource
    private ChargeUserMapper chargeUserMapper;
    @Resource
    private ChargeUserIncomeMapper chargeUserIncomeMapper;
    @Resource
    private ChargeGlobalPropertyMapper chargeGlobalPropertyMapper;

    @Resource
    private RedissonClient redissonClient;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void income(IncomeMessage incomeMessage) {
        ChargeGlobalProperty chargeGlobalProperty = chargeGlobalPropertyMapper.selectByPrimaryKey(1l);
        Integer busyDefault = chargeGlobalProperty.getBusiDefault();
        Long userId = incomeMessage.getUserId();
        RLock lock = redissonClient.getLock(RedisConstantPre.USER_LOCK_PRE + userId);
        lock.lock();
        try {
            //邀请人余额 增加
            ChargeUser chargeUser = chargeUserMapper.selectByPrimaryKey(userId);
            //新余额=当前余额+邀请收益
            chargeUser.setBalance(chargeUser.getBalance().add(new BigDecimal(busyDefault)));
            chargeUserMapper.updateByPrimaryKey(chargeUser);

//            int i=1/0;

            //邀请记录
            ChargeUserIncome chargeUserIncome = new ChargeUserIncome();
            chargeUserIncome.setIncome(new BigDecimal(busyDefault));
            chargeUserIncome.setUserId(incomeMessage.getUserId());
            chargeUserIncome.setCreateTime(incomeMessage.getCreateTime());
            chargeUserIncomeMapper.insert(chargeUserIncome);
        } finally {
            lock.unlock();
        }
    }
}
